package cn.corgy.config;

import cn.corgy.enums.RegisterAndDiscoveryTypeEnum;
import cn.corgy.registry.nacos.utils.NacosUtil;
import cn.corgy.registry.zk.utils.CuratorUtil;
import cn.corgy.remoting.transport.netty.server.NettyRpcServer;
import cn.corgy.utils.concurrent.threadpool.ThreadPoolFactoryUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Objects;

/**
 * 当服务器关闭时，执行一些操作，例如注销所有服务
 */
@Slf4j
public class CustomShutdownHook {

    private static final CustomShutdownHook CUSTOM_SHUTDOWN_HOOK = new CustomShutdownHook();

    public static CustomShutdownHook getCustomShutdownHook() {
        return CUSTOM_SHUTDOWN_HOOK;
    }

    public void clearAll(byte type) {
        log.info("addShutdownHook for clearAll");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getLocalHost().getHostAddress(), NettyRpcServer.PORT);
                if (Objects.equals(RegisterAndDiscoveryTypeEnum.getName(type), "nacos")) {
                    NacosUtil.clearRegistry(NacosUtil.getNacosClient());
                }
                CuratorUtil.clearRegistry(CuratorUtil.getZkClient(), inetSocketAddress);
            } catch (UnknownHostException ignored) {
            }
            ThreadPoolFactoryUtil.shutDownAllThreadPool();
        }));
    }
}
